/**
 * Copyright (c) 2018-2022, NXOS Development Team
 * SPDX-License-Identifier: Apache-2.0
 * 
 * Contains: dma region for old device
 * 
 * Change Logs:
 * Date           Author            Notes
 * 2022-08-13      JasonHu           Init
 */

#include <dma_region.h>
#include <base/page.h>
#include <base/memory.h>

NX_Error NX_DmaAllocBuffer(NX_DmaRegion * d)
{
    if (!d->size || (d->alignment & 0xfff)) /* buffer must page aligned */
    {
        return NX_EINVAL;
    }
    
    int npages = NX_DIV_ROUND_UP(d->size, NX_PAGE_SIZE);
    d->paddr = (NX_Addr)NX_PageAllocInZone(NX_PAGE_ZONE_DMA, npages);
    if(d->paddr == 0)
    {
        return NX_ENOMEM;
    }

    d->vaddr = (NX_Addr) NX_Phy2Virt(d->paddr);
    NX_MemZero((void *)d->vaddr, d->size);
    return NX_EOK;
}

NX_Error NX_DmaFreeBuffer(NX_DmaRegion * d)
{
    if (!d->size || !d->paddr || !d->vaddr)
    {
        return NX_EINVAL;
    }
    
    NX_PageFreeInZone(NX_PAGE_ZONE_DMA, (void *)d->paddr);

    d->paddr = d->vaddr = 0;

    return 0;
}
